/*******************************************************************************
 * The MOSES project, model based software engineering of networked embedded systems.
 * 
 * Copyright (C) 2010-2013, University of Applied Sciences Wildau,
 * Telematics Research Group, http://www.tm.th-wildau.de/research-group
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses>.
 * 
 * Contributors:
 *     University of Applied Sciences Wildau - initial API and implementation
 * 
 * If you are interested in a commercial license please contact us via 
 * e-mail: ralf.vandenhouten@th-wildau.de.
 ******************************************************************************/
package de.thwildau.tm.moses.asn1.ui.builder;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.actions.OrganizeImportsAction;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.statushandlers.StatusManager;
 

/**
 * This BuilderParticipant extends the Xtext-BuilderParticipant (<code>org.eclipse.xtext.builder.BuilderParticipant</code>)
 * with the capability to run the OrganizeImports-Action on the generated resources.
 *
 * @author Thomas Kistel
 * @version $Revision: 767 $
 */
public class OrganizeImportsBuildPart {

    public void build(final IFolder srcFolder) throws CoreException {
        // TODO prevent to be called multiple times
        Display.getDefault().asyncExec(new Runnable() {
            
            @Override
            public void run() {
                try {
                    orgranizeImportsUI(srcFolder);
                } catch (CoreException e) {
                    StatusManager.getManager().handle(e.getStatus());
                }
            }
        });
        
    }
    
    private void orgranizeImportsUI(IFolder srcFolder) throws CoreException {
        IWorkbenchSite site = getWorkbenchSite();
        final List<ICompilationUnit> files = new ArrayList<ICompilationUnit>();
        
        srcFolder.accept(new IResourceVisitor() {
            
            @Override
            public boolean visit(IResource resource) throws CoreException {
                if(isJavaLikeExtension(resource)) {
                    ICompilationUnit cu = JavaCore.createCompilationUnitFrom((IFile) resource);
                    if(cu != null)
                        files.add(cu);
                    return false;
                } 
                // the resource must be a folder, so visit it's members, so return true
                return true;
            }
        });
        
        ICompilationUnit[] cus = files.toArray(new ICompilationUnit[files.size()]);
        
        OrganizeImportsAction action = new OrganizeImportsAction(site);
        action.runOnMultiple(cus);
    }
    
    private boolean isJavaLikeExtension(IResource resource) {
        String fileExtension = resource.getFileExtension();
        if(resource.getType() == IResource.FILE && fileExtension != null) {
            String[] javaLikeExtensions = JavaCore.getJavaLikeExtensions();
            for (String javaLikeExtention : javaLikeExtensions) {
                if(fileExtension.endsWith(javaLikeExtention))
                    return true;
            }
        }
        return false;
    }
    
    private IWorkbenchSite getWorkbenchSite() {
        IWorkbench workbench = PlatformUI.getWorkbench();
        IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
        IWorkbenchPage page = window.getActivePage();
        IWorkbenchPart activePart = page.getActivePart();
        if(activePart == null) {
            activePart = page.findView("org.eclipse.jdt.ui.PackageExplorer");
            page.activate(activePart);
        }
        return activePart.getSite();
    }
}
